<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>面向对象实现canvas动画</title>
</head>

<body>
  <canvas id="myCanvas" width="500" height="500"></canvas>

  <script>
    // 1. 获取画布
    const canvas = document.getElementById("myCanvas");
    // 2. 获取上下文
    const ctx = canvas.getContext("2d");

    function Rect(x, y, width, height, color) {
      // 维护当前设置canvas的状态
      this.x = x;
      this.y = y;
      this.width = width;
      this.height = height;
      this.color = color;
    }

    // 更新的方法
    Rect.prototype.update = function () {
      this.x++;
    }
    // 渲染
    Rect.prototype.render = function () {
      // 设置颜色
      ctx.fillStyle = this.color;
      ctx.fillRect(this.x, this.y, this.width, this.height);
    }

    // 实例化对象
    const obj1 = new Rect(0, 0, 40, 40, "purple");
    const obj2 = new Rect(0, 50, 40, 40, "blue");

    // 动画执行中
    setInterval(function () {
      // 先清屏
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // 更新方法
      obj1.update();
      obj2.update();
      // 渲染方法
      obj1.render();
      obj2.render();
    }, 10)
  </script>

</body>

</html>